﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace XBMC.Cache.Manager
{
    public static class EventLogHelper
    {
        // Set the to be: System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.ToString()
        private static string m_Source = null;
        private static string m_Log = null;

        public static string LogSource
        {
            get { return m_Source; }
            set
            {
                m_Source = value;

                if (m_Source != null && m_Log != null)
                {
                    if (!EventLog.SourceExists(m_Source))
                        EventLog.CreateEventSource(m_Source, m_Log);
                }
            }
        }

        public static string LogName
        {
            get { return m_Log; }
            set
            {
                m_Log = value;

                if (m_Source != null && m_Log != null)
                {
                    if (!EventLog.SourceExists(m_Source))
                        EventLog.CreateEventSource(m_Source, m_Log);
                }
            }
        }

        public static void WriteEvent(string message, EventLogEntryType type)
        {
            try
            {
                if (message.Length > 30000)
                    message = message.Substring(0, 30000);

                EventLog.WriteEntry(m_Source, message, type, 1);
            }
            catch (Exception ex)
            {
                Debugger.Break();
            }
        }

        public static List<EventLogHelperEntry> ReadEventLogEntries()
        {
            EventLog ev = new EventLog(m_Log);
            
            // TODO:DS Add an event notification

            return (from EventLogEntry entry in ev.Entries
                   orderby entry.TimeGenerated descending
                   select new EventLogHelperEntry
                   {
                       Time = entry.TimeGenerated,
                       Source = entry.Source,
                       Message = entry.Message
                   }).ToList();
        }
    }

    public class EventLogHelperEntry
    {
        public DateTime Time { get; set; }
        public string Source { get; set; }
        public string Message { get; set; }
    }
}
